﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
using FamilyBook.Core.Entities;
using FamilyBook.Core.Repositories;
using FamilyBook.Core.Services;
using Microsoft.Practices.Prism.Regions;

namespace FamilyBook.UI.WPF.ViewModels
{
    public class AccountListViewModel : BaseListViewModel<AccountDetailsViewModel>
    {
        private readonly CounterpartyService _counterpartyService;
        private readonly AccountService<Account> _accountService;
        private readonly GeneralService<Product, int> _productService;
        private readonly IList<Currency> _currencies;

        public AccountListViewModel(CounterpartyService counterpartyService,
            AccountService<Account> accountService, 
            GeneralService<Product, int> productService, 
            IGeneralRepository<Currency, string> currRepository)
        {
            _counterpartyService = counterpartyService;
            _accountService = accountService;
            _productService = productService;

            //_counterpartyService.
            _currencies = currRepository.ReadAll().OrderBy(x =>x.Name).ToArray();
            ListModel = new ListCollectionView(_accountService.GetAccounts().Select(x => new AccountDetailsViewModel(x, _currencies, accountService, productService)).ToList());
        }

        protected override AccountDetailsViewModel CreateDetailsViewModel()
        {
            var newAccount = new Account();
            return new AccountDetailsViewModel(newAccount, _currencies, _accountService, _productService);
        }

        protected override void AddNewConfirmed(AccountDetailsViewModel detailsModel)
        {
            Account newAcct = _accountService.Create(detailsModel.Model);
            detailsModel = new AccountDetailsViewModel(newAcct, _currencies, _accountService, _productService);
            base.AddNewConfirmed(detailsModel);
        }

        protected override void ShowDetailsConfirmed(AccountDetailsViewModel detailsModel)
        {
            _accountService.Update(detailsModel.Model);
            base.ShowDetailsConfirmed(detailsModel);
        }
    }
}
